﻿using RRKAutohaus.Core.Repositories;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RRKAutohaus.Core.Helpers
{
    public class RepositoryFactories
    {
        private readonly IDictionary<Type, Func<DbContext, object>> repositoryFactories;

        public RepositoryFactories()
        {
            repositoryFactories = new Dictionary<Type, Func<DbContext, object>>
                {
                    {typeof(ICarRepository), dbContext => new CarRepository(dbContext)}
                };
        }

        public Func<DbContext, object> GetRepositoryFactoryForEntityType<T>() where T : class
        {
            //this will either creates a new repository or gets the current repository ot type T
            return GetRepositoryFactory<T>() ?? DefaultEntityRepository<T>();
        }

        public virtual Func<DbContext, object> GetRepositoryFactory<T>() where T : class
        {
            //this is assumed that the repository has been created
            //this factory will return current repository
            Func<DbContext, object> factory;
            repositoryFactories.TryGetValue(typeof(T), out factory);
            return factory;
        }

        protected virtual Func<DbContext, object> DefaultEntityRepository<T>() where T : class
        {
            //this will create the repository
            return dbContext => new Repository<T>(dbContext);

        }
    }
}
